import Play from '../controller/PlayController/index.js'
import Enemies from '../controller/EnemiesController/index.js'
export default class Main extends Phaser.Scene {
  _levelInfo = null
  constructor() {
    super('main')
    //敌人禁止不动
    this.enemyStop = false
  }

  preload() {
    this._levelInfo = this.sys.game.levelData.levels[this.sys.game.levelData.current] //获取当前关卡信息
    this.enemyNum = this._levelInfo[1]
    this.facing = 0
    this.score = this.enemyNum
    this.isOver = false
  }

  create() {
    this.soundStart = this.sound.add('sound-start') //加载资源
    this.soundFire = this.sound.add('sound-fire')
    this.soundHit = this.sound.add('sound-hit')
    this.soundBoom1 = this.sound.add('sound-boom1')
    this.soundBoom2 = this.sound.add('sound-boom2')
    this.soundWin = this.sound.add('sound-win')
    this.soundOver = this.sound.add('sound-over')
    this.soundStart.play()

    //创建敌人
    this.enemies_class = new Enemies(this)
    this.enemies = this.enemies_class.create_enemy('enemy')
    //获取敌人子弹组
    this.enemyFires = this.enemies_class.create_enemyFires()

    this.player_class_1 = new Play(this) //创建玩家类1
    this.player1 = this.player_class_1.create_play(26 * 8, 38 * 12, 'tank', 1) //获取玩家1
    //获取玩家子弹组
    this.myFires1 = this.player_class_1.getMyFires()

    if (this.sys.game.levelData.ifDouble) {
      this.player_class_2 = new Play(this) //创建玩家类2
      this.player2 = this.player_class_2.create_play(26 * 10.5, 38 * 12, 'tank', 2) //获取玩家2
      this.myFires2 = this.player_class_2.getMyFires()
    }

    this.cursors = this.input.keyboard.createCursorKeys() //创建键盘监听对象

    this.explodes = this.physics.add.group() //创建爆炸组

    this.map = this.make.tilemap({ key: 'levels' }) //创建地图对象
    this.tileset = this.map.addTilesetImage('tile', 'tile')
    this.levelLayer = this.map.createLayer('level-' + (this.sys.game.levelData.current + 1), this.tileset)
    this.levelLayer.setCollisionByProperty({ collides: true }) //设置瓦片自定义属性collides为true的瓦片为碰撞瓦片
    // this.levelLayer.setCollisionByExclusion([0,1,2,3,4,5, 6,7,8,9,10,11,12,13,14], true,this.levelLayer);  //设置瓦片碰撞（方法2）

    // const debugGraphics = this.add.graphics().setAlpha(0.75);   // 碰撞区域可视化
    // this.levelLayer.renderDebug(debugGraphics, {
    //   tileColor: 'ddd', // Color of non-colliding tiles
    //   collidingTileColor: new Phaser.Display.Color(243, 134, 48, 255), // Color of colliding tiles
    //   faceColor: new Phaser.Display.Color(40, 39, 37, 255) // Color of colliding face edges
    // });

    this.physics.world.setBounds(0, 0, this.levelLayer.width, this.levelLayer.height) //设置世界边界
    // this.cameras.main.setBounds(0, 0, this.levelLayer.width, this.levelLayer.height);  //设置相机边界
    // this.physics.world.enable(this.player); //开启物理引擎
    // this.physics.add.collider(this.player, this.levelLayer);  //设置碰撞检测

    this.scoreText = this.add.text(16, 16, 'Enemy: ' + this.score, { fontSize: '16px', fill: '#fff' }) //创建右上角的分数文本
    this.scoreText.setScrollFactor(0)
    this.startAnimation() //开场动画

    // 随机产生bonus并且每隔40s产生一次
    this.bonusTimer = this.time.addEvent({
      delay: 40000,
      callback: this.createBonus,
      callbackScope: this,
      loop: true
    })
  }

  update() {
    if (this.isOver) {
      if (this.cursors.space.isDown) {
        this.actKeyDown(this) //按下空格键事件
      }
      return
    }

    this.player_class_1.update_move() //玩家1移动
    this.player_class_1.actKeyDown() //玩家1按键事件
    this.player_overlap(this.player1, this.myFires1) //玩家1物体碰撞管理

    if (this.sys.game.levelData.ifDouble) {
      this.player_class_2.update_move() //玩家2移动
      this.player_class_2.actKeyDown() //玩家2按键事件
      this.player_overlap(this.player2, this.myFires2) //玩家2物体碰撞管理
    }

    //敌人物体碰撞管理
    this.enemy_overlap(this.enemies, this.enemyFires)

    if (this.bonus) {
      this.physics.collide(this.bonus, this.levelLayer, this.bonus_levelLayer, null, this) //重叠检测
    }

    if (!this.enemyStop && !this.isOver) {
      //敌人行为
      this.enemies_class.update_enemy()
      //随机出生
      this.enemies_class.create_bore()
    } else {
      //敌人全部暂停
      this.enemies.getChildren().forEach(enemy => {
        enemy.setVelocity(0, 0)
      })
    }
  }

  //创建bonus
  createBonus() {
    if (this.bonus) return
    console.log('随机生成道具')
    const tilemap = this.map // 瓦片地图对象
    const tileset = this.tileset // 瓦片集对象
    const layer = this.layer // 瓦片层对象
    let type = Phaser.Math.RND.integerInRange(0, 5) //道具类型

    // 随机生成道具的位置
    let itemX = Phaser.Math.RND.between(0, tilemap.widthInPixels)
    let itemY = Phaser.Math.RND.between(0, tilemap.heightInPixels)

    // 将坐标转换为网格坐标
    const itemTilePosition = tilemap.worldToTileXY(itemX, itemY)

    // 获取该位置的瓦片对象
    const itemTile = tilemap.getTileAt(itemTilePosition.x, itemTilePosition.y, layer)

    // 检查道具位置是否与瓦片重叠
    if (itemTile) {
      // 重新生成道具位置
      this.createBonus()
      console.log('有瓦片')
    } else {
      //清除定时器
      if (this.bonusTimer) this.bonusTimer.remove(false)

      // 道具位置合法，创建道具对象
      this.bonus = this.physics.add.sprite(itemX, itemY, 'bonus', type) // 替换为实际的道具纹理键名
      // 设置其他道具属性等
      this.bonus.setData('type', type)
      // 设置定时器，在10秒后如果bonus仍然存在，则触发消失逻辑
      this.bonusTimer = this.time.delayedCall(7000, this.makeBonusDisappear, [], this)
    }
  }

  makeBonusDisappear() {
    if (this.bonus != null) {
      // 当bonus存在时，触发消失逻辑，并设置闪烁动画定时器
      this.startBlinkAnimation()
      // 设置定时器，在最后3秒触发闪烁动画
      this.bonusTimer = this.time.delayedCall(
        3000,
        () => {
          // 销毁bonus
          this.bonus.destroy()
          this.bonus = null
        },
        [],
        this
      )
    }
  }

  startBlinkAnimation() {
    if (this.bonus != null) {
      // 开始闪烁动画
      this.tweens.add({
        targets: this.bonus,
        alpha: 0, // 透明度为0表示消失
        duration: 200,
        repeat: -1, // 重复无限次
        yoyo: true // 反向播放动画
      })
    }
  }

  //获取bonus
  get_bonus(player, bonus) {
    let play = this['player_class_' + player.getData('play')] //获取玩家
    //播放音效
    this.soundWin.play()
    //根据道具类型执行不同的操作
    switch (this.bonus.getData('type')) {
      case 0:
        //生命+1
        console.log('生命+1')
        break
      case 1:
        console.log('定时')
        this.enemy_Stop()
        break
      case 2:
        console.log('铁铲')
        this.wallToIron()
        break
      case 3:
        this.boom_enemy()
        console.log('手榴弹')
      case 4:
        console.log('五角星')
        play.upgrade()
        break
      case 5:
        console.log('无敌')
        play.makeInvincible(player)
        break
      default:
        break
    }
    bonus.destroy()
    this.bonus = null
  }

  //敌人爆炸
  boom_enemy() {
    this.enemies.getChildren().forEach(enemy => {
      this.explodePlay(enemy.x + 8, enemy.y + 8, 'explode2', 'boom1')
      enemy.destroy()
      this.score--
      if (this.score < 0) {
        this.gameWin()
      }
    })
  }

  //敌人全部禁止不动
  enemy_Stop() {
    //敌人全部暂停
    this.enemyStop = true
    //去掉子弹
    this.enemyFires.getChildren().forEach(fire => {
      //销毁子弹
      fire.setActive(false).setVisible(false)
      fire.destroy()
    })
    setTimeout(() => {
      this.enemyStop = false
    }, 10000)
  }

  //墙体变为铁墙
  wallToIron() {
    let tiles = this.levelLayer.getTilesWithin()
    tiles.forEach(tile => {
      if (tile.index === 1) {
        tile.index = 4
      } else if (tile.index === 3) {
        tile.index = 4
      }
    })
  }

  //爆炸效果
  explodePlay(xx, yy, imageKey, soundKey, timer) {
    timer = timer || 100
    if (soundKey === 'hit') {
      this.soundHit.play()
    } else if (soundKey === 'boom1') {
      this.soundBoom1.play()
    } else if (soundKey === 'boom2') {
      this.soundBoom2.play()
    } else if (soundKey === 'boom3') {
      this.soundWin.play()
    }
    let boom = this.explodes.get(xx, yy, imageKey)
    boom.setOrigin(0.5)
    boom.setScale(0.5)
    this.tweens.add({
      targets: boom,
      scaleX: 1,
      scaleY: 1,
      duration: timer,
      onComplete: function (tween) {
        let target = tween.targets[0]
        target.destroy()
      }
    })
  }

  //按下空格键事件
  actKeyDown() {
    this.scene.start('menu')
  }

  //玩家物体碰撞管理
  player_overlap(player, Fires) {
    //更新
    this.physics.collide(player, this.levelLayer, this.bossHit, null, this) //重叠检测
    this.physics.overlap(Fires, this.levelLayer, this.bossHit, null, this)
    // this.scene.physics.collide(this.myFires, this.scene.levelLayer, this.scene.bossHit, null, this.scene)
    this.physics.overlap(player, this.enemies, this.tankHit, null, this) //碰撞检测

    this.physics.overlap(player, this.enemyFires, this.fireHit, null, this)
    this.physics.overlap(this.enemies, Fires, this.fireHit, null, this)

    this.physics.overlap(Fires, this.levelLayer, this.tileHit, null, this)
    //玩家与道具碰撞
    this.physics.overlap(player, this.bonus, this.get_bonus, null, this)
  }

  //敌人物体碰撞管理
  enemy_overlap(enemy, Fires) {
    this.physics.collide(enemy, this.levelLayer, this.bossHit, null, this)
    this.physics.overlap(Fires, this.levelLayer, this.tileHit, null, this)
    this.physics.overlap(Fires, this.levelLayer, this.bossHit, null, this)
    this.physics.collide(enemy, this.enemies, this.bossHit, null, this)
  }

  //子弹击中坦克事件
  fireHit(tank, fire) {
    this.explodePlay(
      fire.x + (fire.frame.name === 'right' ? 0 : fire.frame.name === 'left' ? 6 : 3),
      fire.y + (fire.frame.name === 'up' ? 0 : fire.frame.name === 'down' ? 6 : 3),
      'explode1'
    )
    fire.destroy()

    //判断坦克是否有护盾且是否是被击中
    if (tank.getData('isPlayer') && tank.getData('isInvincible')) {
      console.log('无敌状态')
      return
    } else {
      if (!tank.getData('isPlayer')) {
        let hp = tank.getData('hp')
        // tank.setData('hp', hp--)
        //判断敌人血量
        if (tank.getData('hp') > 1) {
          hp--
          tank.setData('hp', hp)
          let type = null
          //将hp转化为帧数
          if (hp === 1) {
            type = 36
          } else if (hp === 2) {
            type = 34
          }
          this.explodePlay(tank.x + 8, tank.y + 8, 'explode2', 'boom3')
          this.enemies_class.update_animation(tank, 'enemy', type)
          return
        }
        this.score--
        this.scoreText.setText('Enemy: ' + this.score)
        this.explodePlay(tank.x + 8, tank.y + 8, 'explode2', 'boom1')
        tank.destroy()
        if (this.score < 0) {
          this.gameWin()
        }
      } else {
        this.explodePlay(tank.x + 8, tank.y + 8, 'explode2', 'boom1')
        console.log('玩家' + tank.getData('play') + '被击中')
        tank.destroy()
        //判断是单人还是双人
        if (this.sys.game.levelData.ifDouble) {
          //判断玩是否都死亡
          if (!this.player1.active && !this.player2.active) {
            this.gameOver()
          }
        } else {
          this.gameOver()
        }
      }
    }
  }

  //坦克碰撞事件
  tankHit(tank, tank2) {
    //判断无敌状态
    if (tank.getData('isInvincible')) {
      return
    }

    this.explodePlay(tank.x + 8, tank.y + 8, 'explode2', 'boom1')
    tank.destroy()

    //判断是单人还是双人
    if (this.sys.game.levelData.ifDouble) {
      //判断玩是否都死亡
      if (!this.player1.active && !this.player2.active) {
        this.gameOver()
      }
    } else {
      this.gameOver()
      console.log('碰撞死亡')
    }
  }

  //子弹-瓦片碰撞事件
  tileHit(fire, tile) {
    if ([1, 2, 3, 4].includes(tile.index)) {
      if (tile.life === undefined) {
        //瓦片生命值
        tile.life = tile.index === 3 || tile.index === 4 ? 5 : 2
      }
      //获取子弹等级
      if (tile.index === 4 && (fire.getData('type') == 38 ||fire.getData('type') == 3)) {
        tile.life--
      } else if ([1, 2, 3].includes(tile.index)) {
        tile.life--
      }

      if (tile.life <= 0) {
        //瓦片生命值小于0
        this.map.removeTileAt(tile.x, tile.y, true, true, 'level-' + (this.sys.game.levelData.current + 1))
      }
      this.explodePlay(
        //爆炸效果
        fire.x + (fire.frame.name === 'right' ? 0 : fire.frame.name === 'left' ? 6 : 3),
        fire.y + (fire.frame.name === 'up' ? 0 : fire.frame.name === 'down' ? 6 : 3),
        'explode1',
        'hit'
      )
      fire.destroy() //销毁子弹
    }
  }

  //boss碰撞事件
  bossHit(fire, tile) {
    if ([11, 12, 25, 24].includes(tile.index)) {
      this.explodePlay(tile.getCenterX(), tile.getCenterY(), 'explode2', 'boom2', 300)
      tile.destroy()
      fire.destroy()
      this.gameOver()

      //将boss的瓦片变为铁砖
      let tiles = this.levelLayer.getTilesWithin()
      tiles.forEach(tile => {
        if (tile.index === 11) {
          tile.index = 13
        } else if (tile.index === 12) {
          tile.index = 14
        } else if (tile.index === 25) {
          tile.index = 27
        } else if (tile.index === 24) {
          tile.index = 25
        }
      })
    }
  }

  //游戏结束
  gameOver() {
    this.soundOver.play()
    this.enemyFires.getChildren().forEach(fire => {
      fire.setActive(false).setVisible(false)
    })
    // this.myFires.getChildren().forEach(fire => {
    //   fire.setActive(false).setVisible(false)
    // })
    this.add.sprite(this.cameras.main.centerX, this.cameras.main.centerY + 16, 'over-2')
    let over = this.add.sprite(this.cameras.main.centerX, this.cameras.main.centerY, 'over')
    let over_text = this.add.text(this.cameras.main.centerX / 2, this.cameras.main.centerY, 'Press Space to return', {
      fontSize: '16px',
      fill: '#fff'
    })
    //文字居中
    Phaser.Display.Align.In.Center(over_text, this.levelLayer)
    this.isOver = true
  }

  //游戏胜利
  gameWin() {
    this.soundWin.play()
    this.enemyFires.getChildren().forEach(fire => {
      fire.setActive(false).setVisible(false)
    })
    this.add.sprite(this.cameras.main.centerX, this.cameras.main.centerY, 'over')
    this.add.text(this.cameras.main.centerX, this.cameras.main.centerY, 'Press Space to go to the next level', {
      fontSize: '16px',
      fill: '#fff'
    })

    if (this.sys.game.levelData.current < 3) {
      this.sys.game.levelData.current++ //关卡+1
      // this.registry.set('currentLevel', this.registry.get('currentLevel') + 1)
      this.isOver = true
      //重新渲染
      this.scene.restart()
    }else{
      this.sys.game.levelData.current = 0
      this.scene.start('menu')
    }
  }

  //开场动画
  startAnimation() {
    //关卡开场动画
    // 创建一个黑色的遮罩
    let mask_top = this.add.rectangle(0, 0, this.levelLayer.width, this.levelLayer.height / 2, 0x000000, 1)
    mask_top.setOrigin(0, 0)

    let mask_bottom = this.add.rectangle(
      0,
      this.sys.game.config.height / 2,
      this.levelLayer.width,
      this.levelLayer.height / 2,
      0x000000,
      1
    )
    mask_bottom.setOrigin(0, 0)
    // 显示关卡数
    let levelText = this.add.text(
      this.levelLayer.width / 2,
      this.sys.game.config.height / 2,
      'Level ' + (this.sys.game.levelData.current + 1),
      { fontSize: '20px', fill: '#fff' }
    )
    // levelText.setOrigin(0.5, 0.5);
    //文字居中
    Phaser.Display.Align.In.Center(levelText, this.levelLayer)
    this.tweens.add({
      targets: [mask_top],
      y: -this.levelLayer.height / 2,
      duration: 1500,
      ease: 'none',
      yoyo: false,
      loop: 0
    })

    this.tweens.add({
      targets: [mask_bottom],
      y: this.sys.game.config.height,
      duration: 1500,
      ease: 'none',
      yoyo: false,
      loop: 0
    })

    //关卡等级文字逐渐消失动画
    this.tweens.add({
      targets: [levelText],
      alpha: 0,
      duration: 2000,
      ease: 'none',
      yoyo: false,
      loop: 0
    })
  }
}
